#include <muduo/net/Buffer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpServer.h>
#include <muduo/net/TcpConnection.h>
#include <iostream>
#include <string>
#include <unordered_map>

class DictServer
{
public:
    DictServer(int port)
        :_server(&_baseloop, 
            muduo::net::InetAddress("0.0.0.0", port),
            "DictServer",
            muduo::net::TcpServer::kReusePort)
    {
        //设置事件回调
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(
            std::bind(&DictServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    //启动服务
    void start()
    {
        _server.start(); // 开始监听
        _baseloop.loop(); // 死循环事件监控
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
            std::cout << "连接建立" << std::endl;
        else
            std::cout << "连接断开" << std::endl;
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buff, muduo::Timestamp)
    {
        static std::unordered_map<std::string, std::string> dict_map = 
        {
            {"Hello", "你好"},
            {"你好", "Hello"},
            {"World", "世界"},
            {"世界", "World"},
        };
        std::string msg = buff->retrieveAllAsString();
        std::string ret;
        auto it = dict_map.find(msg);
        if (it == dict_map.end()) 
            ret = "没有对应单词";
        else
            ret = it->second;
        conn->send(ret);
    }

    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServer server(8080);
    server.start();
}